#include "comm/my_rwlock.h"
#include "comm/my_syscall.h"

#define WRITE   4
#define READ    4

#define N       100000

my_rwlock_t lock;
int64_t g_i;

void *
do_write(void *arg) {
    (void)arg;

    for (int i = 0; i < N; i++) {
        my_rwlock_wlock(&lock);
        g_i++;
        my_rwlock_wunlock(&lock);
    }

    return NULL;
}

void *
do_read(void *arg) {
    (void)arg;

    for (int i = 0; i < N; i++) {
        my_rwlock_rlock(&lock);
        for (int j = 0; j < 10; j++) {}
        my_rwlock_runlock(&lock);
    }

    return NULL;
}

int main()
{

    my_rwlock_init(&lock);

    pthread_t tids[WRITE + READ];
    for (int i = 0; i < READ; i++) {
        pthread_t tid;
        pthread_create(&tid, NULL, do_read, NULL);
        tids[i] = tid;
    }

    for (int i = 0; i < WRITE; i++) {
        pthread_t tid;
        pthread_create(&tid, NULL, do_write, NULL);
        tids[i+READ] = tid;
    }

    for (int i = 0; i < READ + WRITE; i++) {
        pthread_join(tids[i], NULL);
    }

    assert(g_i == WRITE * N);


    return 0;
}